package com.dynamic.datasource.connection;

import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 王先堂
 * @Description 连接对象工厂
 * @createTime 2022/03/28/ 15:43:00
 */
public class ConnectionFactory {

    /**
     * 连接代理对象
     */
    private static final ThreadLocal<Map<String, ConnectionProxy>> CONNECTION_LOCAL =
            new ThreadLocal<Map<String, ConnectionProxy>>() {
                @Override
                protected Map<String, ConnectionProxy> initialValue() {
                    return new ConcurrentHashMap<>(8);
                }
            };

    /**
     * 添加连接
     *
     * @param name       数据元名称
     * @param connection 连接代理对象
     */
    public static void putConnection(String name, ConnectionProxy connection) {
        Map<String, ConnectionProxy> concurrentHashMap = CONNECTION_LOCAL.get();
        if (!concurrentHashMap.containsKey(name)) {
            try {
                connection.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            concurrentHashMap.put(name, connection);
        }
    }

    /**
     * 获取连接对象
     *
     * @param name 数据源名称
     * @return ConnectionProxy
     */
    public static ConnectionProxy getConnection(String name) {
        return CONNECTION_LOCAL.get().get(name);
    }

    public static void notify(Boolean state) {
        try {
            Map<String, ConnectionProxy> concurrentHashMap = CONNECTION_LOCAL.get();
            for (ConnectionProxy connectionProxy : concurrentHashMap.values()) {
                connectionProxy.notify(state);
            }
        } finally {
            CONNECTION_LOCAL.remove();
        }
    }
}
